package admin.interceptor;


import admin.common.LoginContext;
import admin.entity.Token;
import admin.entity.User;
import admin.service.TokenService;
import admin.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @author xf07b1
 * @wechat xf07b1
 * @description 认证拦截器
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 校验是否携带token请求头
        String tokenString = request.getHeader("Authorization");
        if (tokenString == null) {
            throw new RuntimeException("Token 为空");
        }

        // 校验token是否过期
        Token token = tokenService.getOne(Wrappers.lambdaQuery(Token.class)
                .eq(Token::getValue, tokenString.substring("Bearer ".length())));
        if ( LocalDateTime.now().isAfter(token.getExpiration())){
            throw new RuntimeException("Token 已过期");
        }

        // 校验token是否有效
        User user = userService.getById(token.getUserId());
        if (user == null){
            throw new RuntimeException("Token 无效");
        }

        LoginContext.set(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginContext.remove();
    }
}